/**
 * Created by XianTao on 2015/1/29
 *
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package com.taotao.wechat.game;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.game.Wheel2Controller;
import com.taotao.rop.database.domain.PlayGame;
import com.taotao.rop.response.BaseResponse;
import com.taotao.rop.util.DateTimeUtil;
import com.taotao.wechat.business.User;
import com.taotao.wechat.message.resp.Article;
import com.taotao.wechat.message.resp.BaseMessage;
import com.taotao.wechat.message.resp.NewsMessage;
import com.taotao.wechat.message.resp.TextMessage;
import com.taotao.wechat.util.MessageUtil;
import com.taotao.wechat.util.ValidateUtil;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 呼伦贝尔 -- 大转盘
 * 时间：2015年2月15日-3月31日--6月30日
 * 规则：
 * 关注呼伦贝尔官方微信的用户，活动期间每天可以获得一次抽奖机会。
 * 话费赠送15天之内上账。
 */
public class WheelGame2 extends Game {
    public static final boolean IS_ENABLE = true;
    private static final String game_url_format = "/game/wheel2/index.html?appId=%s&openId=%s&tel=%s";
    public static final String MSG_TEL_IS_USED = "此手机号码已经被使用";
    public static final String MSG_TEL_IS_USED_NO_MEMBER = "此手机号码已经被使用，请输入“我爱4G”领取升级码继续参与";
    public static final String MSG_MEMBER_CODE_NOT_START = "亲~ 请于每天20:00-21:00输入\"我爱4G\"抢升级码，获得额外抽奖次数，名额有限，先到先得~";
    public static final String MSG_MEMBER_CODE_OVER_COUNT = "亲~ 升级码已被抢光，请于明天晚上再来~";

    public WheelGame2(BaseMessage baseMessage, String content, String appKey) {
        super(baseMessage, content, appKey);
    }

    @Override
    protected String gameUrl() {
        String url = MyRopClient.BASE_URL + String.format(game_url_format, appKey, baseMessage.getToUserName(), content);
        NewsMessage newsMessage = new NewsMessage(baseMessage);
        newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
        newsMessage.setArticleCount(1);
        Article article = new Article();
        article.setDescription("2月15日 - 6月30日期间，关注【内蒙古移动呼伦贝尔分公司】，话费流量专款拿到你手软。");
        article.setPicUrl(MyRopClient.BASE_URL + "/game/wheel2/resource/zt.jpg");
        article.setTitle("天天幸运转，话费转不停");
        article.setUrl(url);
        List<Article> articles = new ArrayList<Article>();
        articles.add(article);
        newsMessage.setArticles(articles);
        return MessageUtil.newsMessageToXml(newsMessage);
    }

    @Override
    protected String inputTelephone() {
        //判断属于哪款游戏
        String currentGameName = getLatestInputGameName(baseMessage.getToUserName(), appKey);
        if (StringUtils.isBlank(currentGameName) || !currentGameName.equalsIgnoreCase(getNickName())) {
            return "";
        }

        //判断活动是否在活动期内
        TextMessage textMessage = new TextMessage(baseMessage);
        Date now = new Date();
        if (DateTimeUtil.compareDate(getStartDate(), now) == 1) {
            textMessage.setContent(getMsgGameNotStart());
        } else if (DateTimeUtil.compareDate(getEndDate(), now) == -1) {
            textMessage.setContent(getMsgGameIsEnd());
        } else {
            //判断是否是内蒙移动手机号
            int telType = ValidateUtil.isYiDong(content, "呼伦贝尔");
            if (telType != 0) {
                if (telType == -1) {
                    textMessage.setContent(getMsgTelNotKnow());
                } else if (telType == 1) {
                    textMessage.setContent(getMsgTelNotNeiMengCMCC());
                } else if (telType == -2) {
                    return "";
                } else if (telType == -3) {
                    textMessage.setContent(msgTelException);
                }
                return MessageUtil.textMessageToXml(textMessage);
            }

            //判断今天是否输入过游戏名字
            if (!hasInputGameNameToday(baseMessage.getToUserName(), appKey)) {
                textMessage.setContent(getMsgTelWithoutGameName());
            } else {
                //判断微信号是否已经超过抽奖次数
                String result = wechatJoinCountToday(baseMessage.getToUserName(), appKey);
                if (StringUtils.isNotBlank(result)
                        && !isMemberTimes.equals(result)) {
                    textMessage.setContent(result);
                } else {
                    //判断手机号是否已经超过抽奖次数
                    result = telJoinCountToday(content, baseMessage.getToUserName(), appKey);
                    if (StringUtils.isNotBlank(result)) {
                        textMessage.setContent(result);
                    } else {
                        //正常参加游戏，返回游戏链接地址
                        return gameUrl();
                    }
                }
            }
        }
        return MessageUtil.textMessageToXml(textMessage);
    }

    @Override
    public String getMsgTelNotNeiMengCMCC() {
        return "您的手机号码不是呼伦贝尔移动号码，请更换手机号码";
    }

    @Override
    public String getAppIds() {
        return "wx13c16cf4b3039116";
    }

    @Override
    public String getMemberCode() {
        return "我爱4G";
    }

    @Override
    public Integer getMemberStatus() {
        return 4;
    }

    @Override
    public String getName() {
        return "大转盘";
    }

    @Override
    public String getNickName() {
        return "wheel2";
    }

    @Override
    public String getStartDate() {
        return "2015-02-15";
    }

    @Override
    public String getEndDate() {
        return "2015-07-01";
    }

    @Override
    protected synchronized String inputMemberCode(Integer memberStatus) {
        if (StringUtils.isBlank(getMemberCode()) || !content.equalsIgnoreCase(getMemberCode())) {
            return "";
        }

        //判断活动是否在活动期内
        TextMessage textMessage = new TextMessage(baseMessage);
        Date now = new Date();
        if (DateTimeUtil.compareDate(getStartDate(), now) == 1) {
            textMessage.setContent(getMsgGameNotStart());
        } else if (DateTimeUtil.compareDate(getEndDate(), now) == -1) {
            textMessage.setContent(getMsgGameIsEnd());
        } else {
            //20:00-21:00，仅限500名
            Long dateStartMillis = DateTimeUtil.getDateStartMillis(now);
            if (now.getTime() < dateStartMillis + 20 * 3600 * 1000L
                    || now.getTime() > dateStartMillis + 21 * 3600 * 1000L) {
                textMessage.setContent(MSG_MEMBER_CODE_NOT_START);
                return MessageUtil.textMessageToXml(textMessage);
            }
            if (Wheel2Controller.counter.get(dateStartMillis) != null
                    && Wheel2Controller.counter.get(dateStartMillis) > 500) {
                textMessage.setContent(MSG_MEMBER_CODE_OVER_COUNT);
                return MessageUtil.textMessageToXml(textMessage);
            }

            //输入游戏会员码，如果存在此用户，则升级成会员；如果不存在此用户，则添加用户并升级成会员
            if (User.setUserToMember(appKey, baseMessage.getToUserName(), memberStatus)) {
                textMessage.setContent(getMsgUpgradeMemberSuccess());
            } else {
                textMessage.setContent(getMsgUpgradeMemberFailure());
            }

            if (Wheel2Controller.counter.get(dateStartMillis) == null
                    || Wheel2Controller.counter.get(dateStartMillis) == 0) {
                Wheel2Controller.counter.clear();
                Wheel2Controller.counter.put(dateStartMillis, 0);
            }
            Wheel2Controller.counter.put(dateStartMillis, Wheel2Controller.counter.get(dateStartMillis) + 1);
        }
        return MessageUtil.textMessageToXml(textMessage);
    }

    @Override
    public String wechatJoinCountToday(String openId, String appKey) {
        PlayGame condition = new PlayGame();
        condition.setAppId(appKey);
        condition.setOpenId(openId);
        condition.setGameName(getNickName());

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.getJoinCountToday", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                int count = (Integer) baseResponse.getData();
                if (isMember(openId, appKey, getMemberStatus())) {
                    if (count >= 2) {
                        return "您今天的次数已经用完";
                    } else if (count == 1){
                        return isMemberTimes;
                    } else {
                        return "";
                    }
                } else {
                    if (count >= 1) {
                        return Wheel2Controller.ALREADY_JOIN_MEMBER;
                    } else {
                        return "";
                    }
                }
            }
        }
        return "系统繁忙，请您稍后再试";
    }

    @Override
    public String telJoinCountToday(String tel, String openId, String appKey) {
        PlayGame condition = new PlayGame();
//        condition.setAppId(appKey);
//        condition.setOpenId(openId);
        condition.setTel(tel);
        condition.setGameName(getNickName());

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.getTelJoinCountToday", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                int count = (Integer) baseResponse.getData();
                if (isMember(openId, appKey, getMemberStatus())) {
                    if (count >= 2) {
                        return MSG_TEL_IS_USED;
                    } else {
                        return "";
                    }
                } else {
                    if (count >= 1) {
                        return MSG_TEL_IS_USED_NO_MEMBER;
                    } else {
                        return "";
                    }
                }
            }
        }
        return "系统繁忙，请您稍后再试";
    }

    @Override
    public String getMsgAfterGameName() {
        return "请输入内蒙古呼伦贝尔移动手机号码参与活动";
    }
}
